<template>
  <div class="room-details">
    <RoomDetailsHeader
      :details="roomDetailsFormat"
      :details-data="roomDetailsData"
    />
    <el-card style="border: none;" shadow="never">
      <el-button
        type="primary"
        :disabled="disabled"
        class="addBtn"
        @click="openDialogEvent"
      >添加人员</el-button>
      <el-table :data="tableData" :header-cell-style="{background: '#f5f7fa'}" border style="width: 100%;">
        <el-table-column prop="user.username" align="center" label="入住人员">
          <template v-slot="{ row }">
            {{ row.user.username }}
            <i
              :class="genderIcon[row.user.gender]"
              style="font-size: 18px;color: #3CD681;"
            />
          </template>
        </el-table-column>
        <el-table-column prop="user.birthday_at" align="center" label="年龄">
          <template v-slot="{ row }">
            {{ getAge(row.user.birthday_at) ?? '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="user.phone" align="center" label="电话" />
        <el-table-column prop="updated_at" align="center" label="入住时间">
          <template v-slot="{ row }">
            {{ timeFormat(row.updated_at) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEditRoom(scope.row.user.id)"
            />
            <el-button
              type="text"
              icon="el-icon-delete"
              class="room-details-delete-btn"
              @click="handleRemovePerson(scope.row.user_id)"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="showAddPerson"
      title="添加人员"
      @closed="closedCallback"
    >
      <el-form
        ref="elForm"
        v-loading="dialogLoading"
        :model="formData"
        :rules="rules"
        label-position="top"
      >
        <el-form-item
          prop="user_id"
          label="选择入住人员(无法选择人员为已离职人员或当前房间人员)："
        >
          <el-select
            v-model="formData.user_id"
            filterable
            :filter-method="handleFilterMethods"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" :loading="loading" @click="addPersonEvent">确定</el-button>
      </span>
    </el-dialog>
    <!-- 修改入住人员 -->
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="showEditUser"
      title="修改入住人员"
    >
      <el-form
        ref="editForm"
        v-loading="dialogLoading"
        :model="editformData"
        label-position="top"
      >
        <el-form-item
          prop="old_user_id"
          label="选择入住人员(无法选择人员为已离职人员或当前房间人员)："
        >
          <el-select
            v-model="editformData.new_user_id"
            filterable
            :filter-method="handleFilterMethods"
            @change="changeRoomUser"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" :loading="loading" @click="editRoomUser">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { addPersonToRoom, room, removePersonFromRoom, editPersonForRoom } from '@/api/v2/dorm'
import { getAllUser, getPersonnelDetails } from '@/api/v2/personnel'
import { handleFiledByID } from '@/utils/handleData'
import dayjs from 'dayjs'
import RoomDetailsHeader from '@/views/dormitory/components/Header/Header.vue'
export default {
  name: '',
  components: {
    RoomDetailsHeader
  },
  data() {
    return {
      loading: false,
      dialogLoading: false,
      options: [],
      showAddPerson: false,
      showEditUser: false,
      roomId: null,
      formData: {
        user_id: null
      },
      editformData: {
        new_user_id: null,
        room_id: null,
        old_user_id: null
      },
      roomDetails: null,
      tableData: [],
      photoInfo: [],
      keywords: '',
      rules: {
        user_id: [
          { required: true, message: '请选择入住人员', trigger: ['blur', 'change'] }
        ]
      },
      genderIcon: {
        0: 'el-icon-female',
        1: 'el-icon-male'
      }
    }
  },
  computed: {
    disabled() {
      return this.roomDetails?.spare_bed <= 0
    },

    roomDetailsFormat() {
      return {
        photo: this.roomDetails?.photo,
        address: `${this.roomDetails?.name}（地址：${this.roomDetails?.dormitory?.address}）`
      }
    },

    roomDetailsData() {
      return [
        { title: '可住人数', icon: 'livable_room', value: this.roomDetails?.number },
        { title: '已住人数', icon: 'lived_room', value: this.roomDetails?.fieldData.length },
        { title: '租金（元）', icon: 'rent', value: this.roomDetails?.rent }
      ]
    }
  },
  watch: {
    // 'formData.user_id': function(n, o) {
    //   if (this.formData.user_id) {
    //     this.getEnterpriseArchives(n)
    //   }
    // }
  },
  created() {
    const { params } = this.$route
    this.roomId = params.id
    this.editformData.room_id = params.id
    this.getRoomDetails()
    // this.getEmployessList()
  },
  methods: {
    async getEmployessList() {
      try {
        const { data } = await getAllUser({
          username: this.keywords,
          // job_status:1,
          type: 2
        })
        this.options = data
          .map(item => ({
            label: item.username,
            value: item.id,
            disabled: handleFiledByID(item.fieldData, 'content', 'job_status') === '0' ||
          this.tableData.some(warp => warp.user.id === item.id)
          }))
      } catch (error) {
        this.$message.error('获取员工信息失败')
        console.log('error ------>', error)
      } finally {
        this.dialogLoading = false
      }
    },
    async getRoomDetails() {
      try {
        const { data } = await room(this.roomId)
        const { photo, rent, name, fieldData } = data
        this.roomDetails = data
        this.tableData = fieldData.map(item => {
          return {
            ...item,
            rent: rent,
            name: name,
            user: this.roomDetailsUserFormat(item.user)
          }
        })
        this.photoInfo = JSON.parse(photo)
      } catch (error) {
        console.log(error)
        this.$message.error('获取详情失败')
      }
    },

    roomDetailsUserFormat(user) {
      return {
        ...user,
        birthday_at: user.field_data.filter(item => item.field_id === 3)[0]?.content
      }
    },

    async handleRemovePerson(id) {
      await this.$confirm('是否将其移除该房间', '提示')
      this.handleRemovePersonApi(id)
    },
    // 删除人员
    async handleRemovePersonApi(id) {
      try {
        const res = await removePersonFromRoom({ user_id: id })
        if (res.status === 'success') {
          this.$message.success('删除成功')
          this.getRoomDetails()
        }
      } catch (error) {
        this.$message.error('删除失败')
      }
    },
    openDialogEvent() {
      this.dialogLoading = true
      this.formData = { user_id: null }
      this.showAddPerson = true
      this.$nextTick(() => {
        this.getEmployessList()
        this.$refs.elForm.clearValidate()
      })
    },
    handleFilterMethods(e) {
      console.log('e ------>', e)
      this.keywords = e
      this.getEmployessList()
    },
    closedCallback() {
      this.keywords = ''
      this.options = []
    },
    async addPersonEvent() {
      await this.$refs.elForm.validate()
      this.getEnterpriseArchives(this.formData.user_id)
      // this.addPersonToRoom()
    },
    // 添加人员
    async addPersonToRoom() {
      this.loading = true
      try {
        const res = await addPersonToRoom(
          { ...this.formData, room_id: this.roomId / 1 }
        )
        console.log('res ------>', res)
        if (res.status === 'success') {
          this.$message.success('添加成功')
          this.closeDialog()
          this.getRoomDetails()
        }
      } catch (error) {
        this.$message.error('添加失败')
        console.log('error ------>', error)
      } finally {
        this.loading = false
      }
    },
    async getEnterpriseArchives(id) {
      if (this.roomDetails.fieldData.length >= this.roomDetails.number) {
        return this.$message.error('当前房间人数已满无法在添加人员')
      }
      try {
        const { data } = await getPersonnelDetails({ user_id: id })
        const roomName = handleFiledByID(data, 'valueType', 'room_id')?.name
        if (roomName) {
          this.$confirm(`该员工已安排${roomName}宿舍，是否继续添加，如添加将会更换宿舍信息`, '提示', {
            type: 'warning'
          }).then(() => {
            this.addPersonToRoom()
          })
        } else {
          this.addPersonToRoom()
        }
      } catch (error) {
        console.log('error ------>', error)
      }
    },
    closeDialog() {
      this.showAddPerson = false
      this.showEditUser = false
    },
    // 打开编辑房间人员
    handleEditRoom(id) {
      this.dialogLoading = true
      this.editformData.old_user_id = id
      this.editformData.new_user_id = id
      this.$nextTick(() => {
        this.getEmployessList()
      })
      this.showEditUser = true
      console.log(id)
    },
    // 修改房间人员
    async editRoomUser() {
      if (this.editformData.old_user_id != this.editformData.new_user_id) {
        try {
          console.log(this.editformData)
          const res = await editPersonForRoom(this.editformData)
          if (res.code === 200) {
            this.$message.success('修改成功')
            this.showEditUser = false
            this.getRoomDetails()
          }
          console.log(res)
        } catch (err) {
          console.log(err)
        }
      } else {
        this.showEditUser = false
      }
    },
    // 监听下拉框选择的内容
    changeRoomUser(value) {
      this.editformData.new_user_id = value || null
    },
    timeFormat(time, format = 'YYYY-MM-DD HH:mm:ss') {
      if (!dayjs(time).isValid()) return ''
      return dayjs(time).format(format)
    },
    getAge(val) {
      if (val) {
        const currentYear = new Date().getFullYear() // 当前的年份
        const calculationYear = new Date(val).getFullYear() // 计算的年份
        const wholeTime = currentYear + val.substring(4) // 周岁时间
        const calculationAge = currentYear - calculationYear // 按照年份计算的年龄
        // 判断是否过了生日
        if (new Date().getTime() > new Date(wholeTime).getTime()) {
          return calculationAge
        } else {
          return calculationAge - 1
        }
      }
      return null
    }
  }
}
</script>

<style scoped lang='scss'>
.room-details {
  padding: 20px;
  .addBtn{
    margin-bottom: 20px;
  }
  &-item {
    display: flex;
    margin-left: 40px;
    margin-top: 20px;
    &-title{
      display: flex;
      align-items: center;
      margin-right: 120px;
      span{
        color: #8e8e8e;
        padding-right: 40px;
      }
    }
  }
  &-photo {
    display: flex;
    align-items: center;
    margin-left: 40px;
    span {
      color: #8e8e8e;
      padding-right: 40px;
    }
    .roomPhoto {
      padding-right: 10px;
      padding-bottom: 20px;
      width: 80px;
      height: 80px;
      .el-image {
        width: 100%;
        height: 100%;
      }
    }
  }
  &-delete-btn{
    color: red;
  }
}
</style>
